import { useEffect, useState } from "react";
import request from "../../axios/request";
import React from "react";
import { Space, Table, Tag } from "antd";
import type { TableProps } from "antd";
import type { FormProps } from "antd";
import { Button, Form, Input, Drawer } from "antd";
import useAuth from "../../hooks/useAuth";
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}
type FieldType = {
  keyword?: string;
  tag?: string;
};
// defaultCurrent={6} total={500}
function Index() {
  useAuth();
  const [shuju, setshuju] = useState([]);
  const [zong, setzong] = useState();
  const [page, setpage] = useState("1");
  const [keyword, setkeyword] = useState("");
  const [pageSize, setpageSize] = useState("10");
  const [bianjiid, setbianjiid] = useState("");
  const columns: TableProps<DataType>["columns"] = [
    {
      title: "Name",
      dataIndex: "title",
      key: "title",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "Age",
      dataIndex: "updatedAt",
      key: "updatedAt",
    },
    {
      title: "Address",
      dataIndex: "content",
      key: "content",
    },

    {
      title: "操作栏",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => shanchu(record.id)}>删除 {record.name}</a>
          <a onClick={() => bianji(record)}>编辑</a>
        </Space>
      ),
    },
  ];

  const dianyong = async () => {
    await request
      .get("/article/list", {
        params: {
          page: page,
          pageSize: pageSize,
          keyword: keyword,
        },
      })
      .then((res) => {
        setshuju(res.data.rows);
        setzong(res.data.count);
      });
  };
  // 分页
  const fenye = (arr, kk) => {
    setpage(arr);
    setpageSize(kk);
  };
  useEffect(() => {
    dianyong();
  }, [page, pageSize, keyword]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
    setkeyword(values.keyword);
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };

  // 删除
  const shanchu = (aaa) => {
    // console.log(id)
    setshuju(shuju.filter((i) => i.id != aaa));
  };
  const [open, setOpen] = useState(false);
  // 新增

  const [title, settitile] = useState("");
  const addshuju = () => {
    setOpen(true);
    settitile("新增");
  };
  const onClose = () => {
    setOpen(false);
  };
  const [xzbj] = Form.useForm();
  // 编辑
  const bianji = (arr) => {
    // console.log(arr);
    setbianjiid(arr.id);
    xzbj.setFieldsValue(arr);
    setOpen(true);
    settitile("编辑");
  };

  // 新增 编辑 提交订单
  const tijiao = async () => {
    const shuju = xzbj.getFieldsValue();
    if (title == "新增") {
      await request
        .post("/article", {
          title: shuju.title,
          content: shuju.content,
          tagList: ["学习"],
          categoryList: ["测试"],
          authorId: 47529555,
        })
        .then((res) => {
          // console.log(res);
          if (res.status == 200) {
            dianyong();
          }
        });
    }
    if (title == "编辑") {
      await request
        .put(`/article/${bianjiid}`, {
          title: shuju.title,
          content: shuju.content,
          tagList: ["学习"],
          categoryList: ["测试"],
        })
        .then((res) => {
          if (res.status == 204) {
            dianyong();
          }
        });
    }
    setOpen(false);
    xzbj.resetFields();
  };
  return (
    <div>
      <Button color="cyan" variant="solid" onClick={addshuju}>
        新增
      </Button>
      {/* 新增的抽屉 */}
      <Drawer
        title={title}
        closable={{ "aria-label": "Close Button" }}
        onClose={onClose}
        open={open}
      >
        <Form
          form={xzbj}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={tijiao}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="文章标题" name="title">
            <Input />
          </Form.Item>

          <Form.Item<FieldType> label="文章内容" name="content">
            <Input />
          </Form.Item>

          <Form.Item label={null}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>

      {/* 搜索 */}
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        layout="inline"
        style={{ maxWidth: 1200 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item<FieldType> label="标题" name="keyword">
          <Input />
        </Form.Item>

        <Form.Item<FieldType> label="标签" name="tag">
          <Input />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>
      <Table<DataType>
        rowKey="id"
        columns={columns}
        dataSource={shuju}
        rowSelection={rowSelection}
        pagination={{
          total: zong,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: fenye,
        }}
      />
    </div>
  );
}

export default Index;
